/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef MSDP_SPATIAL_COMMUNICATOR_H
#define MSDP_SPATIAL_COMMUNICATOR_H

#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

#include "communication_common.h"
#include "icommunicate_interface.h"
#include "spatial_common.h"

namespace OHOS {
namespace Msdp {
class SpatialCommunicator :
    public std::enable_shared_from_this<SpatialCommunicator>,
    public ICommunicateInterface::RemoteListener {
public:
    enum {
        RET_SUCCESS = 0,
        RET_FAILED,
        RET_BUSY,
        RET_NO_NETWORK,
        RET_NOT_CONNECTED,
        RET_NOT_SUPPORTED,
    };
    enum {
        STATE_IDLE = 0,
        STATE_NOT_CONNECTED,
        STATE_CONNECTING,
        STATE_CONNECTED,
        STATE_SERVER_RUNNING,
        STATE_SESSION_OPENING,
        STATE_SESSION_OPENED
    };
    enum {
        ROLE_CLIENT = 0,
        ROLE_SERVER,
    };
    class Session;

    class SpatialSessionListener {
    public:
        SpatialSessionListener() = default;
        virtual ~SpatialSessionListener() = default;
        virtual void OnSessionOpen(std::shared_ptr<Session> session) = 0;
        virtual void OnSessionClose(std::shared_ptr<Session> session) = 0;
        virtual void OnReceiveRequest(std::shared_ptr<Session> session,
            std::shared_ptr<SpatialRequest> request) = 0;
        virtual void OnReceiveResponse(std::shared_ptr<Session> session,
            std::shared_ptr<SpatialResponse> response) = 0;
    };

    class Session {
        friend class SpatialCommunicator;
    public:
        Session(int sessionId, std::shared_ptr<ICommunicateInterface>& adapter,
            const DeviceInfo& device);
        ~Session();
        int GetSessionId();
        void SetSessionId(int sessionId);
        int GetRole();
        DeviceInfo GetDeviceInfo();
        int32_t RequestGetMap();
        int32_t RequestSyncMapOffer(uint32_t topCommit);
        int32_t RequestSyncMap(std::shared_ptr<SpatialMap> map);
        int32_t ResponseGetMap(std::shared_ptr<SpatialMap> map);
        int32_t ResponseSyncMapOffer(bool accept);
        int32_t ResponseSyncMap(bool success);
        void Close();
    private:
        std::shared_ptr<ICommunicateInterface> adapter_;
        int sessionId_;
        DeviceInfo deviceInfo_;
    };

    using DiscoverCallback = std::function<void(DiscoverEvent, const DeviceInfo&)>;
    using ConnectionCallback = std::function<void(ConnectEvent, const DeviceInfo&)>;
    using SessionCallback = std::function<void(std::shared_ptr<Session>)>;
    using GetTrustListCallback = std::function<void(GetDeviceEvent, const std::vector<DeviceInfo>&)>;
    using DeviceStateCallback = std::function<void(DeviceStateEvent, const DeviceInfo&)>;
    SpatialCommunicator();
    virtual ~SpatialCommunicator();

    void Init(std::shared_ptr<ICommunicateInterface> adapter);
    DeviceInfo GetLocalDeviceInfo();
    int32_t StartDiscovery(DiscoverCallback callback);
    int32_t StopDiscovery();
    int32_t GetTrustDeviceList(GetTrustListCallback callback);
    int32_t RegisterDeviceStateListener(DeviceStateCallback callback);
    int32_t UnregisterDeviceStateListener();
    void RegisterSessionListener(const std::shared_ptr<SpatialSessionListener> &sessionListener);

    bool IsDiscoveryComplete();
    bool IsGetDeviceComplete();
    int32_t Connect(const DeviceInfo& device, ConnectionCallback callback);
    bool IsConnected();
    int32_t Disconnect(const DeviceInfo& device);
    int32_t CreateSessionServer();
    int32_t RemoveSessionServer();
    int32_t OpenSession(const DeviceInfo& device);
    int32_t CloseSession(int sessionId);
    bool IsServer(int32_t sessionId);
    std::shared_ptr<Session> GetCommunicatorSession(int sessionId);
    std::shared_ptr<Session> GetCommunicatorSession(const std::string &deviceId);
private:
    friend SpatialCommunicator::Session;
    void OnPublishSuccess() override;
    void OnDiscoverStart() override;
    void OnDiscoverDevice(const DeviceInfo& device) override;
    void OnDiscoverEnd() override;
    void OnConnected(const std::string& networkId) override;
    void OnDisconnected() override;
    int32_t OnSessionOpened(int sessionId, int result) override;
    void OnSessionClosed(int sessionId) override;
    void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) override;
    void OnMessageReceived(int sessionId, const void *data, unsigned int dataLen) override;
    void OnError(int error) override;
    void OnDeviceOnline(const DeviceInfo& device) override;
    void OnDeviceReady(const DeviceInfo& device) override;
    void OnDeviceOffline(const DeviceInfo& device) override;
    void OnDeviceChanged(const DeviceInfo& device) override;
    void OnGetSuccess(const std::vector<DeviceInfo> &deviceInfoList) override;
    void OnGetFail(const std::vector<DeviceInfo> &deviceInfoList) override;
    std::shared_ptr<ICommunicateInterface> adapter_;
    bool discovering_ {false};
    bool getting_ {false};
    uint32_t state_ {STATE_IDLE};
    DiscoverCallback discoverCb_;
    ConnectionCallback connectionCb_;
    GetTrustListCallback trustDeviceCb_;
    DeviceStateCallback stateCb_;
    DeviceInfo connectDevice_;
    DeviceInfo sessionDevice_;
    std::map<std::string, std::shared_ptr<Session>> sessionMap_;

    std::mutex mutex_;
    bool sessionOpenFlag_ {false};
    std::shared_ptr<SpatialSessionListener> sessionListener_;
};
} // namespace Msdp
} // namespace OHOS

#endif // MSDP_SPATIAL_COMMUNICATOR_H
